<!--
 * @Description: File Description
 * @Author: jundie.cheng@hand-china.com
 * @version: H3.0
 * @Date: 2023-03-29 09:32:12
 * @LastEditTime: 2023-03-29 09:43:26
-->
<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('BIWD.FavoriteList.Navigate.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="favorite-view">
      <template v-if="listLoading || favoriteList.length > 0">
        <view class="favorite-list" v-for="(favorite, index) in favoriteList" :key="index">
          <movable-area class="movable-area">
            <movable-view
              class="movable-view"
              direction="horizontal"
              @touchstart="touchstart"
              @htouchmove="touchmove($event, index)"
            >
              <view class="touch-item" :class="{ 'touch-move-active': favorite.isTouchMove }">
                <view class="content favorite-box" @click="jumpToEditFavorite(index)">
                  <view class="favorite-detail">
                    <image class="favorite-img" :src="favorite.img"></image>
                    <view class="favorite-cont">
                      <view class="favorite-name">{{ favorite.name }}</view>
                      <view class="favorite-text">
                        <view>{{ favorite.fav_temp }}<text>℃</text></view>
                        <view class="line"> | </view>
                        <view>{{ (favorite.fav_vol as unknown as number) * 10 }}<text>ml</text></view>
                      </view>
                    </view>
                  </view>
                  <image class="right-arrow" :src="'/static/ic_right_arrow.png'"></image>
                </view>
                <view class="del" @click="deleteFavorite(index)">
                  <view>{{ $t('BIWD.FavoriteList.List.Delete.Button.Text') }}</view>
                </view>
              </view>
            </movable-view>
          </movable-area>
        </view>
      </template>
      <template v-else>
        <view class="no-content">
          <view>{{ $t('BIWD.FavoriteList.NoList.TipsOne.Text') }} </view>
          <view> {{ $t('BIWD.FavoriteList.NoList.TipsTwo.Text') }}</view>
        </view>
      </template>
    </view>

    <template #footer>
      <FooterLayout :size="footerSize" :footer-style="footerStyle">
        <ActionButton @click="jumpToEditFavorite(-1)">+ {{ $t('BIWD.FavoriteList.AddFavorite.Text') }}</ActionButton>
      </FooterLayout>
    </template>

    <Modal v-model:visible="isShowErrorView" title="提示" ok-text="知道了" @ok="hideErrorView">
      <view class="error-text">{{ errorText }}</view>
    </Modal>

    <Modal :visible="favoriteFullVisible" title="提示" ok-text="我知道了" @ok="favoriteFullVisible = false">
      <view class="favorite-full-text">{{ $t('BIWD.FavoriteList.Dialog.FavoriteFullTips.Content.Text') }}</view>
    </Modal>
  </PageLayout>
</template>
<script lang="ts">
export type FavouriteListTypeData = FavouriteListType & {
  img: string
  isTouchMove: boolean
}
export type submitDataType = {
  key: string
  options: {
    key?: string
    value?: string | number
  }[]
  settings: submitSettingType[]
}
export type submitSettingType = {
  key?: string
  value?: string | number
}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import FooterLayout from '@/layout/page/footer.vue'
import Modal from '@/common/modal.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'

import { footerStyle, footerSize } from '@/layout/appliance/style'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getBIWDFavouriteList, type FavouriteListType, setHomeAppliancePrograms, getAllSetting } from '@/api/appliance'
import { favoritePictureListSIEMENS, favoritePictureListBOSCH, NameToArray } from '../filterStatusList'
import { useApplianceStore } from '@/store/appliance'
import netconfig from '@/config/netconfig'
import { actionDebounce, callEventSender, showLoading, toPage, useEventReceiver } from '@/utils/mpHelper'
import {
  DatConfig,
  DatConfig_SetCollect,
  CollectionOperation,
  CollectionOperation_Delete,
  DatConfig_DeleteCollect,
} from '@/constants/WDCommand'
import { useI18n } from 'vue-i18n'
import type { BIWDController } from '@/controller/BIWD/definition'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { applianceControlTrack, safeTrack } from '@/dataReport/dataReportUtil'
import { loadDatasource, loadFileModule } from '@/controller/demo/utils'

const i18n = useI18n()
const headerStyle = {
  backgroundColor: '#fff',
}
const control = ref<BIWDController.Control | null>(null)
const isVirtual = ref(false)
useEventReceiver('control', (received: BIWDController.Control) => {
  control.value = received
})

const haId = ref('')
const isBOSCHBIWD = computed(() => haId.value.split('-')[0].toUpperCase() !== 'SIEMENS')

const favoriteList = ref<FavouriteListTypeData[]>([])
const listLoading = ref(true)
const isShowErrorView = ref(false)
const errorText = ref('')
const isCallApi = ref(false)
const favoriteFullVisible = ref(false)

onLoad((query: any) => {
  haId.value = query?.haId
  isVirtual.value = query?.isVirtual === 'true'
})

onShow(() => {
  getFavoriteListFun()
})

/**
 * 获取收藏列表
 */
async function getFavoriteListFun() {
  await showLoading(async () => {
    listLoading.value = true
    try {
      let data: FavouriteListType[] = []
      if (isVirtual.value) {
        const datasource = await loadFileModule<{ DemoFavouriteList: FavouriteListType[] }>('/demo/BIWD/data')
        data = datasource.DemoFavouriteList
      } else {
        const res = await getBIWDFavouriteList(haId.value)
        data = res.data.data
      }

      favoriteList.value = data.map((item) => {
        let imgUrl = isBOSCHBIWD.value
          ? favoritePictureListBOSCH[item.fav_pic as unknown as number].url
          : favoritePictureListSIEMENS[item.fav_pic as unknown as number].url
        return {
          ...item,
          img: netconfig.ASSETSPRE_ICONS + imgUrl,
          isTouchMove: false,
        }
      })
    } catch (error) {
      isShowErrorView.value = true
      errorText.value = '获取收藏程序列表失败'
    } finally {
      listLoading.value = false
    }
  }, i18n.t('BIWD.FavoriteList.Loading.Text'))
}
/**
 * 添加收藏
 */
const jumpToEditFavorite = actionDebounce({
  call: async (index: number) => {
    if (!isVirtual.value) {
      if (!checkHomeApplianceState()) return
    }
    if (listLoading.value) return
    if (index === -1 && favoriteList.value.length >= 9) {
      favoriteFullVisible.value = true
      return
    }
    const res = await toPage('/pages/appliance/BIWD/addFavorite/addFavorite', {
      haId: haId.value,
      index,
      favoriteList: JSON.stringify(favoriteList.value),
      isVirtual: isVirtual.value,
    })
    callEventSender(res.eventChannel, 'control', control.value)
  },
})

/**
 * 打开确定删除提示框
 * @param index
 */
function deleteFavorite(index: number) {
  if (!checkHomeApplianceState()) return
  uni.showModal({
    title: i18n.t('BIWD.FavoriteList.List.Delete.Dialog.Text'),
    content: i18n.t('BIWD.FavoriteList.List.Delete.Dialog.Content.Text'),
    success(res) {
      if (res.confirm) {
        deleteFavoriteList(index)
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}
/**
 * 删除收藏程序
 * @param index
 */
const deleteFavoriteList = actionDebounce({
  loadingText: i18n.t('BIWD.FavoriteList.List.Delete.Loading.Text'),
  call: async (index: number) => {
    if (isVirtual.value) {
      getFavoriteListFun()
      uni.showToast({
        title: '删除成功',
        icon: 'success',
      })
      return
    }
    if (!checkHomeApplianceState()) return
    try {
      isCallApi.value = true
      let deteleFavoriteDetail = favoriteList.value[index]
      safeTrack(() => {
        trackEvent(
          'before_delete_favorite_program',

          {
            program_key: control.value?.store.currentProgramKey,
            program_name: control.value?.store.currentProgramName,
            favorite_value_obj: {
              favourite_program_name: deteleFavoriteDetail.name,
              temperature: deteleFavoriteDetail.fav_temp,
              drink_type: deteleFavoriteDetail.img.replace(netconfig.ASSETSPRE_ICONS, '').split('.')[0],
              volume: deteleFavoriteDetail.fav_vol,
            },
          },
          TrackType.ApplianceDetail,
          'Appliance.BIWD.Deletefavorite.Favorite'
        )
      })

      let nameArray = NameToArray(deteleFavoriteDetail.name)
      let submitData: submitDataType = {
        key: 'BSH.Collect.Program.Selected.FavoriteProgram' + (index + 1),
        options: [],
        settings: [],
      }
      if (!isBOSCHBIWD.value) {
        submitData.settings.push(
          {
            key: DatConfig,
            value: DatConfig_SetCollect,
          },
          {
            key: CollectionOperation,
            value: CollectionOperation_Delete,
          }
        )
      } else {
        submitData.settings.push({
          key: DatConfig,
          value: DatConfig_DeleteCollect,
        })
      }
      submitData.settings.push(
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name1',
          value: nameArray[0],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name2',
          value: nameArray[1],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name3',
          value: nameArray[2],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name4',
          value: nameArray[3],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name5',
          value: nameArray[4],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name6',
          value: nameArray[5],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name7',
          value: nameArray[6],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name8',
          value: nameArray[7],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name9',
          value: nameArray[8],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Name10',
          value: nameArray[9],
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Temp',
          value: parseInt(deteleFavoriteDetail.fav_temp),
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Volume',
          value: parseInt(deteleFavoriteDetail.fav_vol),
        },
        {
          key: 'WaterTreatment.BIWD.Setting.FavoriteProgram1Picture',
          value: parseInt(deteleFavoriteDetail.fav_pic),
        }
      )
      applianceControlTrack(
        () => setHomeAppliancePrograms(haId.value, submitData),
        'delete_favorite_program',
        {
          program_key: control.value?.store.currentProgramKey,
          program_name: control.value?.store.currentProgramName,
          favorite_value_obj: {
            favourite_program_name: deteleFavoriteDetail.name,
            temperature: deteleFavoriteDetail.fav_temp,
            drink_type: deteleFavoriteDetail.img.replace(netconfig.ASSETSPRE_ICONS, '').split('.')[0],
            volume: deteleFavoriteDetail.fav_vol,
          },
        },
        'Appliance.BIWD.Deletefavorite.Favorite'
      )
      favoriteList.value.splice(index, 1)
      uni.hideLoading()
      isCallApi.value = false
    } catch (error) {
      uni.hideLoading()
      isShowErrorView.value = true
      errorText.value = '删除收藏程序失败'
      isCallApi.value = false
    }
  },
})

function hideErrorView() {
  isShowErrorView.value = false
}
/**
 * 检查净饮器状态
 */
function checkHomeApplianceState() {
  let isCan = true
  if (isCallApi.value == true) {
    //净饮机正在进行api调用
    isCan = false
  } else if (control.value?.store.runState == -1) {
    //获取净饮机状态失败
    isShowErrorView.value = true
    errorText.value = '获取家电运行状态失败'
    isCan = false
  } else if (control.value?.store.runState == 3) {
    //净饮机处于运行状态
    isCan = false
    isShowErrorView.value = true
    errorText.value = '机器正在出水中，暂无法使用小程序控制家电'
  } else if (control.value?.store.isLocalOperate) {
    //净饮机处于本地操作状态
    isCan = false
    isShowErrorView.value = true
    errorText.value = '机器正在被本地操作，暂无法使用小程序控制家电'
  }
  return isCan
}

/**
 * 滑动删除
 */
const startX = ref(0)
const startY = ref(0)
function touchstart(e: TouchEvent) {
  startX.value = e.changedTouches[0].pageX
  startY.value = e.changedTouches[0].pageY
}
function touchmove(e: TouchEvent, index: number) {
  const pageX = e.changedTouches[0].pageX //结束时X坐标
  const pageY = e.changedTouches[0].pageY //结束时Y坐标
  const newStartX = startX.value //开始时X坐标
  const newStartY = startY.value //开始时Y坐标
  // 获取滑动角度
  const angles: number = angle(
    {
      X: newStartX,
      Y: newStartY,
    },
    {
      X: pageX,
      Y: pageY,
    }
  )
  favoriteList.value.forEach((item, i) => {
    if (angles > 30) {
      return
    }
    if (i == index) {
      if (startX.value < pageX) {
        //右滑
        item.isTouchMove = false
      } else {
        //左滑
        item.isTouchMove = true
      }
    }
  })
}
function angle(start: { X: number; Y: number }, end: { X: number; Y: number }) {
  var _X = start.X - end.X
  var _Y = start.Y - end.Y
  return (360 * Math.atan(_Y / _X)) / (2 * Math.PI)
}
</script>
<style scoped lang="less">
.favorite-view {
  padding: 16rpx 32rpx 20rpx 0;
  .right-arrow {
    width: 16rpx;
    height: 28rpx;
  }
  .movable-area {
    width: 100%;
    height: 184rpx;
  }
  .movable-view {
    width: 100%;
    height: 184rpx;
  }
  .touch-item {
    display: flex;
    justify-content: space-between;
    height: 184rpx;
    overflow: hidden;
    padding-left: 32rpx;
  }
  .touch-move-active .del {
    background-color: #fff;
  }

  .touch-move-active .content,
  .touch-move-active .del {
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }

  .content {
    width: 100%;
    -webkit-transition: all 0.4s;
    transition: all 0.4s;
    -webkit-transform: translateX(140rpx);
    transform: translateX(140rpx);
    margin-left: -140rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .del {
    width: 140rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--danger-color);
    -webkit-transform: translateX(140rpx);
    transform: translateX(140rpx);
    -webkit-transition: all 0.4s;
    transition: all 0.4s;
    // border-top-right-radius: 20rpx;
    // border-bottom-right-radius: 20rpx;
  }

  .favorite-list {
    margin-bottom: 16rpx;
    height: 184rpx;
  }

  .favorite-box {
    height: 184rpx;
    background-color: #f4f4f6;
    padding: 24rpx 28rpx 24rpx 24rpx;
    box-sizing: border-box;
    position: relative;
    .favorite-detail {
      display: flex;
      .favorite-img {
        width: 136rpx;
        height: 136rpx;
        margin-right: 24rpx;
      }
      .favorite-name {
        font-weight: 500;
        font-size: 32rpx;
        line-height: 44rpx;
        color: var(--dark-color);
      }
      .favorite-text {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 28rpx;
        line-height: 40rpx;
        color: var(--dark-color);
        opacity: 0.8;
        margin-top: 8rpx;
        .line {
          width: 34rpx;
          text-align: center;
        }
      }
    }
  }

  .favoriteBoxInfo {
    width: 200rpx;
    height: 184rpx;
  }

  .favoriteImg {
    width: 136rpx;
    height: 136rpx;
    border-radius: 16rpx;
  }

  .favoriteBoxInfoImage {
    position: relative;
    width: 100rpx;
    height: 100rpx;
    margin: 20rpx auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .favoriteBoxInfoImageView {
    position: absolute;
    width: 100rpx;
    height: 100rpx;
    background: #ffffff;
    opacity: 0.1;
    border-radius: 50%;
  }

  .favoriteBoxInfo .img {
    width: 64rpx;
  }

  .favoriteBoxInfoTitle {
    font-family: PingFangSC-Semibold;
    font-size: 28rpx;
    color: #ffffff;
    letter-spacing: -0.68rpx;
    text-align: center;
  }
}
.no-content {
  width: 100%;
  height: 100%;
  text-align: center;
  margin-top: 80%;
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  color: var(--dark-color);
}
</style>
